package com.mz.ozy.activity.home;

import android.Manifest;
import android.app.Activity;
import android.content.Intent;
import android.graphics.Typeface;
import android.os.Bundle;
import android.text.SpannableString;
import android.text.Spanned;
import android.text.TextUtils;
import android.text.method.LinkMovementMethod;
import android.util.Log;
import android.util.TypedValue;
import android.view.Gravity;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.GridView;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;

import androidx.core.content.ContextCompat;
import androidx.recyclerview.widget.GridLayoutManager;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import com.chad.library.adapter.base.BaseQuickAdapter;
import com.luck.picture.lib.PictureSelector;
import com.luck.picture.lib.config.PictureConfig;
import com.luck.picture.lib.config.PictureMimeType;
import com.mz.ozy.R;
import com.mz.ozy.activity.MainActivity;
import com.mz.ozy.activity.find.StrategyDetailActivity;
import com.mz.ozy.activity.login.SplashActivity;
import com.mz.ozy.activity.me.CustomServiceActivity;
import com.mz.ozy.activity.me.MsgActivity;
import com.mz.ozy.activity.me.MsgDetailActivity;
import com.mz.ozy.activity.me.ObShopActivity;
import com.mz.ozy.activity.me.ObShopActivity1;
import com.mz.ozy.activity.me.ObShopListActivity;
import com.mz.ozy.activity.me.UpVipActivity;
import com.mz.ozy.activity.shop.CarActivity;
import com.mz.ozy.activity.shop.SearchActivity;
import com.mz.ozy.activity.shop.ShopDetailActivity;
import com.mz.ozy.activity.shop.SortSearchActivity;
import com.mz.ozy.activity.shop.TopicListActivity;
import com.mz.ozy.adapter.AdverAdapter;
import com.mz.ozy.adapter.HomeFlGridAdapter;
import com.mz.ozy.adapter.HomeSortAdapter;
import com.mz.ozy.adapter.HomeTopicAdapter;
import com.mz.ozy.adapter.HomeTopicAdapter1;
import com.mz.ozy.adapter.ObHomeGoodsAdapter;
import com.mz.ozy.adapter.ObShopAdapter;
import com.mz.ozy.adapter.OrderMsgAdapter;
import com.mz.ozy.base.BaseActivity;
import com.mz.ozy.bean.CheckBean;
import com.mz.ozy.bean.DbBean;
import com.mz.ozy.bean.EventBean;
import com.mz.ozy.bean.GoodsListBean;
import com.mz.ozy.bean.HomeMerBean;
import com.mz.ozy.bean.MyOrderInfoBean1;
import com.mz.ozy.bean.ObShopBean;
import com.mz.ozy.bean.UnreadMsgBean;
import com.mz.ozy.constants.Constants;
import com.mz.ozy.mvp.presenter.HomePresenter;
import com.mz.ozy.mvp.view.HomeContract;
import com.mz.ozy.utils.AddrDbManager;
import com.mz.ozy.utils.AppUtils;
import com.mz.ozy.utils.LocationHelper;
import com.mz.ozy.utils.SPUtils;
import com.mz.ozy.utils.ScreenUtil;
import com.mz.ozy.utils.ToastUtils;
import com.mz.ozy.utils.Utils;
import com.mz.ozy.utils.glideUtils.GlideUtils;
import com.mz.ozy.widget.BannerViewPager;
import com.mz.ozy.widget.LoginButtonSpan;
import com.mz.ozy.widget.MarqueeView;
import com.mz.ozy.widget.dialog.BaseDialog;
import com.mz.ozy.widget.dialog.CheckDialog;
import com.mz.ozy.widget.dialog.NotVipDialog;
import com.scwang.smartrefresh.layout.SmartRefreshLayout;
import com.scwang.smartrefresh.layout.api.RefreshLayout;
import com.scwang.smartrefresh.layout.listener.OnRefreshListener;
import com.scwang.smartrefresh.layout.listener.OnRefreshLoadmoreListener;
import com.socks.library.KLog;
import com.tbruyelle.rxpermissions.RxPermissions;
import com.yanzhenjie.permission.AndPermission;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;
import org.json.JSONObject;

import java.util.ArrayList;
import java.util.List;
import java.util.Timer;
import java.util.TimerTask;

import androidx.recyclerview.widget.StaggeredGridLayoutManager;
import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import rx.functions.Action1;

public class HomeActivity1 extends BaseActivity<HomeContract.View, HomePresenter> implements HomeContract.View {

    @BindView(R.id.view_recy_home)
    BannerViewPager viewRecyHome;
    @BindView(R.id.view_recy_home_rl)
    LinearLayout viewRecyHomeRl;
    @BindView(R.id.smartRefreshLayout)
    SmartRefreshLayout mRefreshLayout;
    //    @BindView(R.id.rv_green_food)
//    RecyclerView mRvGreenFood;
//    @BindView(R.id.rv_organic_food)
//    RecyclerView mRvOrganicFood;
    @BindView(R.id.rv_sort_food)
    RecyclerView mRvSortFood;
    @BindView(R.id.flGridView)
    GridView flGridView;
    @BindView(R.id.rv_home_food_list)
    RecyclerView mRvHomeFoodList;
    @BindView(R.id.rv_home_food_list2)
    RecyclerView mRvHomeFoodList1;
    @BindView(R.id.ll_food_tab)
    LinearLayout mLlFoodTab;
    @BindView(R.id.carNumberTv)
    TextView mCarNumberTv;//购物车数量
    @BindView(R.id.tv_home_city)
    TextView mTvHomeCity;//城市
    @BindView(R.id.iv_vip_entry)
    ImageView mIvVipEntry;//城市
    @BindView(R.id.rv_adver_banner)
    RecyclerView mRvAdverBanner;//城市
    @BindView(R.id.rv_ob_shop)
    RecyclerView mRvObShop;
    @BindView(R.id.ll_ob_tab)
    LinearLayout mLlObTab;
    @BindView(R.id.marqueeView)
    MarqueeView marqueeView;
    @BindView(R.id.image_ordermsg)
    ImageView mImageOrdermsg;
    @BindView(R.id.ll_ob_shop)
    LinearLayout mLlObShop;

    private List<TextView> mTabTvs = new ArrayList<>();
    private List<View> mTabViews = new ArrayList<>();
    private HomeSortAdapter mHomeSortAdapter;
    private HomeFlGridAdapter homeFlGridAdapter;
    private HomeTopicAdapter mHomeTopicAdapter;
    private HomeTopicAdapter1 mHomeTopicAdapter1;
    private AdverAdapter mAdverAdapter;
    private List<HomeMerBean.CanListBean> canListBeans = new ArrayList<>();
    private List<HomeMerBean.SpecialListBean> ztListTopic = new ArrayList<>();
    private List<HomeMerBean.SpecialList> ztListTopic1 = new ArrayList<>();
    private List<HomeMerBean.SpecialListBean> ztListSort = new ArrayList<>();
    private List<HomeMerBean.SpecialListBean> ztList3 = new ArrayList<>();
    private List<HomeMerBean.ProductListBean> ztProductList3 = new ArrayList<>();
    private List<HomeMerBean.ProductListBean> ztProductListSort = new ArrayList<>();
    private List<String> msgStrList = new ArrayList<>();
    private List<HomeMerBean.MsgListBean> mMsgListBeans = new ArrayList<>();
    private boolean isRefreshCar = false;
    private boolean isFirst = true;
    private boolean isAuthFirst = true;
    private int foodType = 0;
    private String cityCode;
    private HomeMerBean content;
    private int page=0;

    private ObHomeGoodsAdapter mObShopAdapter;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_home1);
        ButterKnife.bind(this);
        EventBus.getDefault().register(this);
        titleBar = findViewById(R.id.titleBar);
        setTitleBarMargin();
        mTvHomeCity.setText(LocationHelper.getCity());
        initRefreshLayout();
        initView();
        initEvents();
//        initOpenStorage();
//        String is_tip = SPUtils.getInstance(this).getString(Constants.SPName.IS_TIP, "");
//        if (!"1".equals(is_tip)) {
//            TipsDialog();
//        }
        mPresenter.getHomeInfo(this, isFirst);
//        mPresenter.getOrMer(this);
        isFirst = false;
        mPresenter.checkUpdateVersion(this);
        //mPresenter.getProduct(this,page+"");

        RxPermissions.getInstance(HomeActivity1.this)
                .request(Manifest.permission.ACCESS_FINE_LOCATION)
                .subscribe(new Action1<Boolean>() {
                    @Override
                    public void call(Boolean aBoolean) {
                        if (aBoolean) {
                            requestLocation();
                        } else {
                            Log.i("permissions", "权限获取失败");
                        }
                    }
                });
    }

    private boolean mBackKeyPressed;

    /**
     * 第四种方法
     */
    @Override
    public void onBackPressed() {
        if (!mBackKeyPressed) {
            Toast.makeText(this, "再按一次退出欧卓雅", Toast.LENGTH_SHORT).show();
            mBackKeyPressed = true;
            new Timer().schedule(new TimerTask() {
                @Override
                public void run() {
                    mBackKeyPressed = false;
                }
            }, 2000);
        } else {
            finish();
        }
    }

    private void initOpenStorage() {
        RxPermissions.getInstance(this)
                .request(Manifest.permission.WRITE_EXTERNAL_STORAGE, Manifest.permission.READ_EXTERNAL_STORAGE)
                .subscribe(new Action1<Boolean>() {
                    @Override
                    public void call(Boolean aBoolean) {
                        if (aBoolean) {
                            AddrDbManager.loadAddressData(HomeActivity1.this);
                        } else {
                            ToastUtils.showToast("为了功能正常使用，请您开启存储权限");
                        }
                    }
                });
//        AndPermission.with(this).permission(Manifest.permission.WRITE_EXTERNAL_STORAGE, Manifest.permission.READ_EXTERNAL_STORAGE)
//
//                .onGranted(permissions -> {
//                    AddrDbManager.loadAddressData(HomeActivity1.this);
//                })
//                .onDenied(permissions -> {
//                    ToastUtils.showToast("为了功能正常使用，请您开启存储权限");
//                })
//                .start();
    }

//    private void TipsDialog() {
//        final BaseDialog dialog = new BaseDialog(HomeActivity1.this, R.layout.dialog_login_private, Gravity.CENTER, false);
//        final TextView tvContent = dialog.getView(R.id.tv_dialog_content);
//        setMsgContent(tvContent);
//        ((TextView) dialog.getView(R.id.tv_dialog_title)).setText("温馨提示");
//        ((TextView) dialog.getView(R.id.btn_cancel)).setText("暂不使用");
//        ((TextView) dialog.getView(R.id.btn_cancel)).setTextColor(getResources().getColor(R.color.c_333333));
//        ((TextView) dialog.getView(R.id.btn_confirm)).setText("同意");
//        ((TextView) dialog.getView(R.id.btn_confirm)).setTextColor(getResources().getColor(R.color.c_047aff));
//        dialog.getView(R.id.btn_cancel).setOnClickListener(new View.OnClickListener() {
//            @Override
//            public void onClick(View v) {
//                dialog.toggleDialog();
////                finish();
//            }
//        });
//        dialog.getView(R.id.btn_confirm).setOnClickListener(new View.OnClickListener() {
//            @Override
//            public void onClick(View v) {
//                SPUtils.getInstance(HomeActivity1.this).putString(Constants.SPName.IS_TIP, "1");
//                dialog.toggleDialog();
//                reLocation();
//                initOpenStorage();
////                isAuthFirst = false;
//            }
//        });
//        dialog.toggleDialog();
//    }

    @Override
    protected void onResume() {
        super.onResume();
        if(Constants.isLogin) {
            mPresenter.getUnreadMsg(this);
        }

        String is_tip = SPUtils.getInstance(this).getString(Constants.SPName.IS_TIP, "");
        if ("1".equals(is_tip)) {
            requestLocation();
        }
    }

    public void requestLocation() {
        LocationHelper.setOnLocationListener(new LocationHelper.onLocationListener() {
            @Override
            public void locationSuccess() {
                if (TextUtils.isEmpty(LocationHelper.getCity())) {
                    mTvHomeCity.setText("未知");
                } else {
                    mTvHomeCity.setText(LocationHelper.getCity());
                }
            }
        });
        LocationHelper.initLocationOption();
    }

//    private void setMsgContent(TextView tvContent) {
//        tvContent.setText("欢迎来到欧卓雅，感谢您对欧卓雅的信任和支持！\n" +
//                "为了保障客户端的正常运行以及能够向您提供更全面的功能服务，我们将通过《服务协议》和《隐私政策》帮助您了解我们收集、使用、存储和共享个人信息的情况，以及您所享有的相关权利。\n" +
//                "具体内容请您详阅");
//        String content = "《用户协议》";
//        SpannableString userSpanStr = new SpannableString(content);
//        LoginButtonSpan span = new LoginButtonSpan(this, new View.OnClickListener() {
//            @Override
//            public void onClick(View v) {
//                CustomServiceActivity.go(HomeActivity1.this, 0);
//            }
//        }, R.color.c_047aff);
//        userSpanStr.setSpan(span, 0, content.length(), Spanned.SPAN_INCLUSIVE_EXCLUSIVE);
//        tvContent.append(userSpanStr);
//        tvContent.append("和");
//        String content2 = "《隐私政策》";
//        SpannableString userSpanStr2 = new SpannableString(content2);
//        LoginButtonSpan span2 = new LoginButtonSpan(this, new View.OnClickListener() {
//            @Override
//            public void onClick(View v) {
//                CustomServiceActivity.go(HomeActivity1.this, 1);
//            }
//        }, R.color.c_047aff);
//        userSpanStr2.setSpan(span2, 0, content2.length(), Spanned.SPAN_INCLUSIVE_EXCLUSIVE);
//        tvContent.append(userSpanStr2);
//        tvContent.append("全文，我们已采用业内先进的信息保护措施，并会持续优化信息保护技术和安全管理流程，来保护您的个人信息安全。");
//        tvContent.setMovementMethod(LinkMovementMethod.getInstance());
//    }


    private void initEvents() {
        flGridView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {

//                if(!Constants.isVip){
//                    showVipDialog();
//                    return;
//                }
                final HomeMerBean.CanListBean homeMerBean = (HomeMerBean.CanListBean) homeFlGridAdapter.getItem(position);
//                switch (homeMerBean.getTitle()) {
                switch (homeMerBean.getType()) {
//                switch (position) {
//                    case "礼尚往来":

                    case 0: {
//                        ToastUtils.showToast("敬请期待");

                        final Intent intent = new Intent(HomeActivity1.this, ReciprocityActivity.class);
                        intent.putExtra("title", homeMerBean.getTitle());
                        startActivity(intent);
                        break;
                    }
                    case 1: {
//                        ToastUtils.showToast("敬请期待");
                        final Intent intent = new Intent(HomeActivity1.this, PrivateCustomActivity.class);
                        intent.putExtra("title", homeMerBean.getTitle());
                        startActivity(intent);
                        break;
                    }
                    case 2: {
                        final Intent intent = new Intent(HomeActivity1.this, IdyllicPastureActivity.class);
                        intent.putExtra("title", homeMerBean.getTitle());
                        startActivity(intent);
                        break;
                    }
                    case 3: {
                        //         ToastUtils.showToast("暂未开放");
                        final Intent intent = new Intent(HomeActivity1.this, OrganicActivity.class);
                        intent.putExtra("title", homeMerBean.getTitle());
                        startActivity(intent);
                        break;
                    }
                    case 4: {
//                        ToastUtils.showToast("敬请期待");
                        final Intent intent = new Intent(HomeActivity1.this, LiveRoomActivity.class);
                        intent.putExtra("title", homeMerBean.getTitle());
                        startActivity(intent);
                        break;
                    }
                    case 5: {
                        final Intent intent = new Intent(HomeActivity1.this, ScheduledDeliveryActivity.class);
                        intent.putExtra("title", homeMerBean.getTitle());
                        startActivity(intent);
                        break;
                    }
                    case 6: {
//                        ToastUtils.showToast("敬请期待");
                        final Intent intent = new Intent(HomeActivity1.this, PopularActivity.class);
                        intent.putExtra("title", homeMerBean.getTitle());
                        startActivity(intent);
                        break;
                    }
                    case 7: {
                        final Intent intent = new Intent(HomeActivity1.this, ShogakuinActivity.class);
                        intent.putExtra("title", homeMerBean.getTitle());
                        startActivity(intent);
                        break;
                    }
                }
            }
        });
        mHomeSortAdapter.setOnItemChildClickListener(new BaseQuickAdapter.OnItemChildClickListener() {
            @Override
            public void onItemChildClick(BaseQuickAdapter adapter, View view, int position) {
//                if(!Constants.isVip){
//                    showVipDialog();
//                    return;
//                }
                final HomeMerBean.ProductListBean productListBean = (HomeMerBean.ProductListBean) adapter.getItem(position);
                switch (view.getId()) {
                    case R.id.ll_item_view: {
                        Intent intent = new Intent(HomeActivity1.this, ShopDetailActivity.class);
                        intent.putExtra("goodsId", productListBean.getId() + "");
                        startActivity(intent);
                        break;
                    }
                    case R.id.iv_sort_car: {
                        Intent intent = new Intent(HomeActivity1.this, ShopDetailActivity.class);
                        intent.putExtra("goodsId", productListBean.getId() + "");
                        intent.putExtra("show", 1);
                        startActivity(intent);
                        break;
                    }
                }
            }
        });

        mObShopAdapter.setOnItemChildClickListener(new BaseQuickAdapter.OnItemChildClickListener() {
            @Override
            public void onItemChildClick(BaseQuickAdapter adapter, View view, int position) {
//                if(!Constants.isVip){
//                    showVipDialog();
//                    return;
//                }
                final HomeMerBean.ProductListBean productListBean = (HomeMerBean.ProductListBean) adapter.getItem(position);
                switch (view.getId()) {
                    case R.id.ll_item_view: {
                        Intent intent = new Intent(HomeActivity1.this, ShopDetailActivity.class);
                        intent.putExtra("goodsId", productListBean.getId() + "");
                        startActivity(intent);
                        break;
                    }
                    case R.id.iv_sort_car: {
                        Intent intent = new Intent(HomeActivity1.this, ShopDetailActivity.class);
                        intent.putExtra("goodsId", productListBean.getId() + "");
                        intent.putExtra("show", 1);
                        startActivity(intent);
                        break;
                    }
                }
            }
        });
        marqueeView.setOnItemClickListener(new MarqueeView.OnItemClickListener() {
            @Override
            public void onItemClick(int position, TextView textView) {
//                if(!Constants.isVip){
//                    showVipDialog();
//                    return;
//                }
                Intent intent = new Intent(HomeActivity1.this, MsgDetailActivity.class);
                intent.putExtra("id", mMsgListBeans.get(position).getId());
                intent.putExtra("title", mMsgListBeans.get(position).getTitle());
                intent.putExtra("time", mMsgListBeans.get(position).getCreated());
                intent.putExtra("content", mMsgListBeans.get(position).getContent());
                startActivity(intent);
            }
        });
        mAdverAdapter.setOnItemClickListener(new BaseQuickAdapter.OnItemClickListener() {
            @Override
            public void onItemClick(BaseQuickAdapter adapter, View view, int position) {
                final HomeMerBean.BannerListBean item = mAdverAdapter.getItem(position);
                if (TextUtils.isEmpty(item.getRef())) {
                    return;
                }
//                if(!Constants.isVip){
//                    showVipDialog();
//                    return;
//                }
                if (item.getType() == 0) {
                    Intent intent = new Intent(HomeActivity1.this, ShopDetailActivity.class);
                    intent.putExtra("goodsId", item.getRef());
                    startActivity(intent);
                } else {

                    Intent intent = new Intent(HomeActivity1.this, StrategyDetailActivity.class);
                    intent.putExtra(StrategyDetailActivity.ARTICLE_ID, Integer.parseInt(item.getRef()));
                    startActivity(intent);
                }
            }
        });

    }

    private void initView() {
        homeFlGridAdapter = new HomeFlGridAdapter(this, canListBeans);
        flGridView.setAdapter(homeFlGridAdapter);

        mRvAdverBanner.setLayoutManager(new LinearLayoutManager(this));
        mAdverAdapter = new AdverAdapter(this, new ArrayList<>());
        mRvAdverBanner.setAdapter(mAdverAdapter);

        mObShopAdapter = new ObHomeGoodsAdapter(ztProductList3);
        mRvObShop.setLayoutManager(new StaggeredGridLayoutManager(2, StaggeredGridLayoutManager.VERTICAL));
        mRvObShop.setAdapter(mObShopAdapter);

        mHomeTopicAdapter = new HomeTopicAdapter(this,ztListTopic);
        mRvHomeFoodList.setLayoutManager(new LinearLayoutManager(this));
        mRvHomeFoodList.setAdapter(mHomeTopicAdapter);

        mHomeTopicAdapter1 = new HomeTopicAdapter1(this,ztListTopic1);
        mRvHomeFoodList1.setLayoutManager(new LinearLayoutManager(this));
        mRvHomeFoodList1.setAdapter(mHomeTopicAdapter1);

        mRvSortFood.setLayoutManager(new LinearLayoutManager(this));
        mRvSortFood.setNestedScrollingEnabled(false);
        mHomeSortAdapter = new HomeSortAdapter(ztProductListSort);
        mRvSortFood.setAdapter(mHomeSortAdapter);
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        EventBus.getDefault().unregister(this);
    }


    private void initRefreshLayout() {
        //mRefreshLayout.setEnableLoadmore(false);
//        mRefreshLayout.setOnRefreshListener(new OnRefreshListener() {
//            @Override
//            public void onRefresh(RefreshLayout refreshlayout) {
//                mPresenter.getHomeInfo(HomeActivity1.this, isFirst);
////                reLocation();
//            }
//        });
        mRefreshLayout.setEnableLoadmore(true);
        mRefreshLayout.setOnRefreshLoadmoreListener(new OnRefreshLoadmoreListener() {
            @Override
            public void onLoadmore(RefreshLayout refreshlayout) {
                //tag = 1;
                page = page + 1;
                mPresenter.getProduct(HomeActivity1.this, page + "");
            }

            @Override
            public void onRefresh(RefreshLayout refreshlayout) {
                mPresenter.getHomeInfo(HomeActivity1.this, isFirst);
            }
        });

//        mRefreshLayout.setEnableAutoLoadmore(true);
//        mRefreshLayout.setOnRefreshLoadmoreListener(new OnRefreshLoadmoreListener() {
//            @Override
//            public void onLoadmore(RefreshLayout refreshlayout) {
//                page = page + 1;
//                mPresenter.getProduct(HomeActivity1.this,page+"");
//            }
//
//            @Override
//            public void onRefresh(RefreshLayout refreshlayout) {
//
//            }
//        });
    }

    private void reLocation() {
        if (!LocationHelper.isIsLocate()) {
            RxPermissions.getInstance(this)
                    .request(Manifest.permission.ACCESS_FINE_LOCATION, Manifest.permission.ACCESS_COARSE_LOCATION)//这里填写所需要的权限
                    .subscribe(new Action1<Boolean>() {
                        @Override
                        public void call(Boolean aBoolean) {
                            if (aBoolean) {//true表示获取权限成功（注意这里在android6.0以下默认为true）
                                LocationHelper.setOnLocationListener(new LocationHelper.onLocationListener() {
                                    @Override
                                    public void locationSuccess() {
                                        if (TextUtils.isEmpty(LocationHelper.getCity())) {
                                            mTvHomeCity.setText("未知");
                                        } else {
                                            mTvHomeCity.setText(LocationHelper.getCity());
                                        }
                                    }
                                });
                                LocationHelper.initLocationOption();
                                isAuthFirst = false;
                            } else {
                                ToastUtils.showToast("为了功能正常使用，请您开启定位权限");
                            }
                        }
                    });
//            AndPermission.with(this).permission(Manifest.permission.ACCESS_FINE_LOCATION, Manifest.permission.ACCESS_COARSE_LOCATION)
//
//                    .onGranted(permissions -> {
//                        LocationHelper.setOnLocationListener(new LocationHelper.onLocationListener() {
//                            @Override
//                            public void locationSuccess() {
//                                if (TextUtils.isEmpty(LocationHelper.getCity())) {
//                                    mTvHomeCity.setText("未知");
//                                } else {
//                                    mTvHomeCity.setText(LocationHelper.getCity());
//                                }
//                            }
//                        });
//                        LocationHelper.initLocationOption();
//                    })
//                    .onDenied(permissions -> {
//                        ToastUtils.showToast("为了功能正常使用，请您开启定位权限");
//                    })
//                    .start();
        } else {
            if (TextUtils.isEmpty(LocationHelper.getCity())) {
                mTvHomeCity.setText("未知");
            } else {
                mTvHomeCity.setText(LocationHelper.getCity());
            }
        }
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onMessageEvent(EventBean event) {
        //刷新购物车
        if (event.getCode() == Constants.EventCode.REFRESH_CAR) {
            isRefreshCar = true;
            mPresenter.getHomeInfo(HomeActivity1.this, isFirst);
        }
    }

    @Override
    public void checkUpdateVersionSuccess(CheckBean json) {
        if (json != null) {
            int vnumber = json.getVersionMapaz().getVnumber();

            if (vnumber > Utils.getVersionCode(this)) {
                new CheckDialog(HomeActivity1.this, json).show();

            }

        }
    }

    @Override
    public void getMyMerSuccess(HomeMerBean homeMerBean) {
/* HomeMerBean.BannerListBean bannerListBean = new HomeMerBean.BannerListBean();
        bannerListBean.setImg_url("sdad");
        bannerListBean.setCreated("eqewe");
        urlList1.add(0,bannerListBean);*/

        homeFlGridAdapter = new HomeFlGridAdapter(this, homeMerBean.getCateList());
        flGridView.setAdapter(homeFlGridAdapter);
    }

    @Override
    public void getOrSuccess(HomeMerBean o) {
        content = o;
    }

    @Override
    public void getHomeInfoSuccess(HomeMerBean homeMerBean) {
        if (homeMerBean.getIsPwd() == 0) {
            mPresenter.exitLogin(this);
        }
//        if(Constants.isLogin) {
//            mPresenter.getUnreadMsg(this);
//        }
        mRefreshLayout.finishRefresh();
        if (homeMerBean.getBuyCarNum() == 0) {
            mCarNumberTv.setVisibility(View.GONE);
        } else {
            mCarNumberTv.setText(String.valueOf(homeMerBean.getBuyCarNum()));
            mCarNumberTv.setVisibility(View.VISIBLE);
        }
        if (isRefreshCar) {
            isRefreshCar = false;
            return;
        }
        viewRecyHome.removeConfig();
        viewRecyHome.initBanner(homeMerBean.getBannerList(), true)//开启3D画廊效果
                .addPageMargin(0, 20)//参数1page之间的间距,参数2中间item距离边界的间距
                .addStartTimer(5)//自动轮播5秒间隔
                .addPointBottom(7).addRoundCorners(12)//圆角
                .addPoint(10)
                .finishConfig()//这句必须加
                .addBannerListener(new BannerViewPager.OnClickBannerListener() {

                    @Override
                    public void onBannerClick(int position, String s) {
                        //点击item
                        ToastUtils.showToast(s);
                    }
                });
        viewRecyHome.addBannerListener(new BannerViewPager.OnClickBannerListener() {
            @Override
            public void onBannerClick(int position, String s) {
                final HomeMerBean.BannerListBean bannerListBean = viewRecyHome.getList().get(position);
                if (TextUtils.isEmpty(bannerListBean.getRef())) {
                    return;
                }
//                if(!Constants.isVip){
//                    showVipDialog();
//                    return;
//                }
                if (bannerListBean.getType() == 0) {
                    Intent intent = new Intent(HomeActivity1.this, ShopDetailActivity.class);
                    intent.putExtra("goodsId", bannerListBean.getRef());
                    startActivity(intent);
                } else {
                    Intent intent = new Intent(HomeActivity1.this, StrategyDetailActivity.class);
                    intent.putExtra(StrategyDetailActivity.ARTICLE_ID, Integer.parseInt(bannerListBean.getRef()));
                    startActivity(intent);
                }
            }
        });
        mMsgListBeans.clear();
        msgStrList.clear();
        final List<HomeMerBean.MsgListBean> msgList = homeMerBean.getMsgList();
        if (msgList != null && msgList.size() > 0) {
            mMsgListBeans.addAll(msgList);
            for (int i = 0; i < msgList.size(); i++) {
                msgStrList.add(msgList.get(i).getTitle());
            }
            marqueeView.startWithList(msgStrList);
        }

        canListBeans.clear();
        canListBeans.addAll(homeMerBean.getCateList());
        homeFlGridAdapter.notifyDataSetChanged();

        ztListSort.clear();
        ztListTopic.clear();
        final List<HomeMerBean.SpecialListBean> ztList = homeMerBean.getZtList1();
        if (ztList != null && ztList.size() > 0) {
            for (HomeMerBean.SpecialListBean ztBean : ztList) {
                if (ztBean.getSystemType() == 0) {
                    ztListSort.add(ztBean);
                } else if (ztBean.getSystemType() == 1) {
                    ztListTopic.add(ztBean);
                }
            }
        }

        if (ztListTopic != null && ztListTopic.size() > 0) {
            mHomeTopicAdapter.notifyDataSetChanged();
        }

        ztListTopic1.clear();
        final List<HomeMerBean.SpecialListBean> ztList2 = homeMerBean.getZtList();
        if (ztList2 != null && ztList2.size() > 0) {
            HomeMerBean.SpecialList specialList = new HomeMerBean.SpecialList();
            specialList.setSpecialList(ztList2);
            ztListTopic1.add(specialList);
        }

        if (ztListTopic1 != null && ztListTopic1.size() > 0) {
            mHomeTopicAdapter1.notifyDataSetChanged();
        }

        ztList3.clear();
        final List<HomeMerBean.SpecialListBean> ztList31 = homeMerBean.getZtList3();
        if (ztList31 != null && ztList31.size() > 0) {
            for (HomeMerBean.SpecialListBean ztBean : ztList31) {
                ztList3.add(ztBean);
            }
        }

        if (ztList3 != null && ztList3.size() > 0) {
            mObShopAdapter.notifyDataSetChanged();
        }

        page = 0;

        handleTopicSort();

        handleztList3();

        final List<HomeMerBean.BannerListBean> conAdverBannerList = homeMerBean.getConAdverBannerList();
        if (conAdverBannerList != null && conAdverBannerList.size() > 0) {
            mAdverAdapter.setNewData(conAdverBannerList);
        }
        final List<HomeMerBean.BannerListBean> vipBannerList = homeMerBean.getVipBannerList();
        if (vipBannerList != null && vipBannerList.size() > 0) {
            GlideUtils.loadRoundImg(this, mIvVipEntry, vipBannerList.get(0).getImgPath(), R.mipmap.bg_vip_entry, 4);
        }
    }

    @Override
    public void exitLoginSuccess(JSONObject bean) {
        AppUtils.resetStaticData(this);
    }

    @Override
    public void getUnreadMsgSuccess(UnreadMsgBean bean) {
        if(bean.getNums()>0) {
            mImageOrdermsg.setVisibility(View.VISIBLE);
        }
        else
        {
            mImageOrdermsg.setVisibility(View.GONE);
        }
    }

    @Override
    public void getProductSuccess(ObShopBean bean) {
        final List<ObShopBean.PBean.PageItemsBean> prodcut_list = bean.getPage().getPageItems();
        List<HomeMerBean.ProductListBean> productList = new ArrayList<>();
        if(prodcut_list !=null && prodcut_list.size()>0)
        {
            for(int i=0;i<prodcut_list.size();i++)
            {
                ObShopBean.PBean.PageItemsBean productBean = prodcut_list.get(i);
                HomeMerBean.ProductListBean productListBean = new HomeMerBean.ProductListBean();
                productListBean.setId(productBean.getId());
                productListBean.setDescribed(productBean.getDescribed());
                productListBean.setImg_zt(productBean.getImg_zt());
                productListBean.setMarket_price(productBean.getMarket_price());
                productListBean.setPrice(productBean.getPrice());
                productListBean.setShopbv(productBean.getShopbv());
                productListBean.setTradename(productBean.getTradename());
                productListBean.setWeight(productBean.getWeight());

                productList.add(productListBean);
            }
        }
        ztProductList3.addAll(productList);
        //mObShopAdapter.setNewData(productList);
        mObShopAdapter.notifyDataSetChanged();
        mRefreshLayout.finishLoadmore();
    }

    private void handleTopicSort() {
//        if(Constants.isLogin) {
//            mPresenter.getUnreadMsg(this);
//        }
        if (ztListSort != null && ztListSort.size() > 0) {
            mTabTvs.clear();
            mTabViews.clear();
            mLlFoodTab.removeAllViews();
            for (int i = 0; i < ztListSort.size(); i++) {
                HomeMerBean.SpecialListBean sortBean = ztListSort.get(i);
                View sortTab = View.inflate(this, R.layout.tab_home_layout, null);
                if (i == 0) {
                    mLlFoodTab.addView(sortTab);
                } else {
                    LinearLayout.MarginLayoutParams sortParams = new LinearLayout.LayoutParams(ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.WRAP_CONTENT);
                    sortParams.leftMargin = ScreenUtil.dip2px(this, 25);
                    mLlFoodTab.addView(sortTab, sortParams);
                }
                TextView tvFoodTab = sortTab.findViewById(R.id.tv_all_food);
                mTabTvs.add(tvFoodTab);
                View viewFoodTab = sortTab.findViewById(R.id.view_all_food);
                mTabViews.add(viewFoodTab);
                tvFoodTab.setText(sortBean.getTitle());
                if (i == 0) {
                    mTvCurrent = tvFoodTab;
                    mViewCurrent = viewFoodTab;
                    tvFoodTab.setTextSize(TypedValue.COMPLEX_UNIT_DIP, 15);
                    tvFoodTab.setTextColor(ContextCompat.getColor(HomeActivity1.this, R.color.c_363636));
                    tvFoodTab.setTypeface(Typeface.defaultFromStyle(Typeface.BOLD));
                    viewFoodTab.setVisibility(View.VISIBLE);

                    ztProductListSort.clear();
                    ztProductListSort.addAll(sortBean.getProductList());
                    mHomeSortAdapter.notifyDataSetChanged();
                }

                final int index = i;
                sortTab.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View view) {
                        changeCurrentTab(index);
                    }
                });
            }
        }
    }

    private void handleztList3() {
//        if(Constants.isLogin) {
//            mPresenter.getUnreadMsg(this);
//        }
        if (ztList3 != null && ztList3.size() > 0) {
            mTabTvs.clear();
            mTabViews.clear();
            mLlObTab.removeAllViews();
            for (int i = 0; i < ztList3.size(); i++) {
                HomeMerBean.SpecialListBean sortBean = ztList3.get(i);
                View sortTab = View.inflate(this, R.layout.tab_home_layout, null);
                if (i == 0) {
                    mLlObTab.addView(sortTab);
                } else {
                    LinearLayout.MarginLayoutParams sortParams = new LinearLayout.LayoutParams(ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.WRAP_CONTENT);
                    sortParams.leftMargin = ScreenUtil.dip2px(this, 25);
                    mLlObTab.addView(sortTab, sortParams);
                }
                TextView tvFoodTab = sortTab.findViewById(R.id.tv_all_food);
                mTabTvs.add(tvFoodTab);
                View viewFoodTab = sortTab.findViewById(R.id.view_all_food);
                mTabViews.add(viewFoodTab);
                tvFoodTab.setText(sortBean.getTitle());
                if (i == 0) {
                    mTvCurrent = tvFoodTab;
                    mViewCurrent = viewFoodTab;
                    tvFoodTab.setTextSize(TypedValue.COMPLEX_UNIT_DIP, 15);
                    tvFoodTab.setTextColor(ContextCompat.getColor(HomeActivity1.this, R.color.c_363636));
                    tvFoodTab.setTypeface(Typeface.defaultFromStyle(Typeface.BOLD));
                    viewFoodTab.setVisibility(View.VISIBLE);

                    ztProductList3.clear();
                    ztProductList3.addAll(sortBean.getProductList());
                    mObShopAdapter.notifyDataSetChanged();

                    if(sortBean.getProductList().size()==0)
                    {
                        mLlObShop.setVisibility(View.GONE);
                        mRefreshLayout.finishLoadmore();
                    }else {
                        mLlObShop.setVisibility(View.VISIBLE);
                    }
                }

                final int index = i;
                sortTab.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View view) {
                        changeCurrentTab(index);
                    }
                });
            }
        }
    }

    @OnClick({R.id.tv_more, R.id.iv_home_msg, R.id.iv_home_car, R.id.tv_search, R.id.ll_address
            , R.id.iv_vip_entry})
    public void onViewClicked(View view) {

        if(view.getId()==R.id.iv_home_msg){
            startActivity(new Intent(this, MsgActivity.class));
            return;
        }

//        if(!Constants.isVip){
//            showVipDialog();
//            return;
//        }
        switch (view.getId()) {
            case R.id.tv_more:
                startActivity(new Intent(this, MsgActivity.class));
                break;
            case R.id.iv_home_msg:
                startActivity(new Intent(this, MsgActivity.class));
                break;
            case R.id.tv_search:
                startActivity(new Intent(this, SearchActivity.class));
                break;
            case R.id.iv_home_car:
                startActivity(new Intent(this, CarActivity.class));
                break;
            case R.id.ll_address:
//                Intent intent = new Intent(this, CitySelectActivity.class);
//                startActivityForResult(intent, 101);
                break;
            case R.id.iv_vip_entry:
                startActivity(new Intent(this, ObShopActivity1.class));
                break;
        }
    }

    TextView mTvCurrent;
    View mViewCurrent;

    private void changeCurrentTab(int type) {
        TextView textView = mTabTvs.get(type);
        View tabview = mTabViews.get(type);
        if (mTvCurrent != textView) {
            mTvCurrent.setTextSize(TypedValue.COMPLEX_UNIT_DIP, 13);
            mTvCurrent.setTextColor(ContextCompat.getColor(HomeActivity1.this, R.color.c_a5a5a5));
            mTvCurrent.setTypeface(Typeface.defaultFromStyle(Typeface.NORMAL));
            mViewCurrent.setVisibility(View.INVISIBLE);
            textView.setTextSize(TypedValue.COMPLEX_UNIT_DIP, 15);
            textView.setTextColor(ContextCompat.getColor(HomeActivity1.this, R.color.c_363636));
            textView.setTypeface(Typeface.defaultFromStyle(Typeface.BOLD));
            tabview.setVisibility(View.VISIBLE);
            mTvCurrent = textView;
            mViewCurrent = tabview;
            foodType = type;

            ztProductListSort.clear();
            ztProductListSort.addAll(ztListSort.get(type).getProductList());
            mHomeSortAdapter.notifyDataSetChanged();
        }
    }

    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (requestCode == 101 && resultCode == 101) {
            DbBean dbBean = (DbBean) data.getSerializableExtra("dbbean");
            cityCode = dbBean.getId();
            KLog.e("",dbBean.getAreaName());
            mTvHomeCity.setText(dbBean.getAreaName());
        }
    }
}
